/*
	Copyright (C) 2013 Pontificia Universidad Catolica del Peru
	contact: http://avatar.inf.pucp.edu.pe/realidad-aumentada/
	address contact: Av. Universitaria 1801, San Miguel, Lima-Peru.
	
	This file is part of UbicAR PUCP.

	This program is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with This program.  If not, see <http://www.gnu.org/licenses/>.
*/
/*
	Authors: Alvaro Roger Agüero Sánchez, Rodolfo Javier Galvez Meza
	Pontificia Universidad Catolica del Peru
	Departamento de Ingeniería
*/

package org.grupoavatar.guiaubicua.punto;

import org.grupoavatar.guiaubicua.R;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
//import android.graphics.Picture;
import android.os.Bundle;
import android.os.Message;
//import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
//import android.webkit.WebView.PictureListener;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;

@SuppressLint({ "SetJavaScriptEnabled", "SetJavaScriptEnabled" })
public class Comentarios extends MasterActivity {

	//private ArrayList<String> imagenes;
	//private String requestUrl="http://avatar.inf.pucp.edu.pe/guiaubicua/fb/comments.html";
	private String requestUrl="http://ubicar.inf.pucp.edu.pe/Ubicua/punto_comment/";
	//private String requestUrl="file:///sdcard/guiaUbicuaPUCP/comments.html";
	private WebView webView,childView =null;
	private LinearLayout parentLayout;
	private Activity MyActivity;
	
	//private boolean ejecutoJs = false;
    
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		//this.getWindow().requestFeature(Window.FEATURE_PROGRESS);
		setContentView(R.layout.comentarios);
		
		requestUrl =requestUrl +marker.getPOI().getId();
		/*
		btnGeneral.setSelected(true);
		btnGeneral.setClickable(false);

		btnUbicacion.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				Intent intent = new Intent(Comentarios.this, TabUbicacion.class);
				startActivity(intent);
				overridePendingTransition(0, 0);
				finish();
				overridePendingTransition(0, 0);
			}
		});

		btnServicios.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				Intent intent = new Intent(Comentarios.this, TabServicios.class);
				startActivity(intent);
				overridePendingTransition(0, 0);
				finish();
				overridePendingTransition(0, 0);
			}
		});
		 */
		//boolean mostrarLayout = false;
		
		//Cabecera
//		TextView lblNombre = (TextView) findViewById(R.id.lblNombre);
//		lblNombre.setText(poi.getTitle());
//		TextView lblCategoria = (TextView) findViewById(R.id.lblCategoria);
//		lblCategoria.setText(MixContext.getDataSourceName(poi.getDatasource()));
//		
//		ImageView imageCate = (ImageView) this.findViewById(R.id.imgCategoria);
//        Bitmap bitfile_cate = ((ArpucpPOIMarker)poi).getDataSourceCircleIconRA(this.getResources());                
//        imageCate.setImageBitmap(bitfile_cate);  
        
        //botones
        
        btnGeneral.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				Intent intent = new Intent(Comentarios.this, TabGeneral.class);
				pasarDatos();
				startActivity(intent);
				overridePendingTransition(0, 0);
				finish();
				overridePendingTransition(0, 0);
			}
		});

		btnServicios.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				Intent intent = new Intent(Comentarios.this, TabServicios.class);
				pasarDatos();
				startActivity(intent);
				overridePendingTransition(0, 0);
				finish();
				overridePendingTransition(0, 0);
			}
		});
		
		btnUbicacion.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				Intent intent = new Intent(Comentarios.this, TabUbicacion.class);
				pasarDatos();
				startActivity(intent);
				overridePendingTransition(0, 0);
				finish();
				overridePendingTransition(0, 0);
			}
		});
		
        //Comentarios
        
        getWindow().setFeatureInt(Window.FEATURE_PROGRESS,Window.PROGRESS_VISIBILITY_ON);
	    parentLayout =(LinearLayout)findViewById(R.id.commentsLayout);


	    MyActivity = this;


	    webView = new WebView(this);
	    //webView.setWebViewClient(new WebClient());
	    //webView.setPictureListener(new MyPictureListener());
	    //webView.setBackgroundResource(R.drawable.logonyancat);
	    webView.setLayoutParams(getLayoutParams());
	    
	    webView.setHorizontalScrollBarEnabled(false);
	    webView.setHorizontalFadingEdgeEnabled(false);
	    webView.setHorizontalScrollbarOverlay(false);
	    
	    webView.setWebViewClient(new FaceBookClient());
	    webView.setWebChromeClient(new MyChromeClient());
	    webView.getSettings().setJavaScriptEnabled(true);
	    webView.getSettings().setAppCacheEnabled(true);
	    webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
	    webView.getSettings().setSupportMultipleWindows(true);
	    	    
	    webView.getSettings().setSupportZoom(false);
	    webView.getSettings().setBuiltInZoomControls(false);
	    webView.getSettings().setSavePassword(true);
	    
	    /*
	    if (Utiles.isTablet(MyActivity))
	    	webView.getSettings().setDefaultZoom(WebSettings.ZoomDensity.CLOSE);
	    else
	    	webView.getSettings().setDefaultZoom(WebSettings.ZoomDensity.MEDIUM);
	    */	
	    
	    //webView.getSettings().setLoadWithOverviewMode(true);
	    //webView.getSettings().setUseWideViewPort(true);	
	    
	    parentLayout.addView(webView);
	    
	    try{
	    	webView.loadUrl(requestUrl);
	    } catch (Exception e) {
            e.printStackTrace();
        }
		
	}
	
	private LinearLayout.LayoutParams getLayoutParams(){
	    return new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT); 
	}


	final class MyChromeClient extends WebChromeClient{
	    @Override
	    public boolean onCreateWindow(WebView view, boolean dialog,
	            boolean userGesture, Message resultMsg) {
	    	
	        childView = new WebView(Comentarios.this);
	        childView.getSettings().setJavaScriptEnabled(true);
	        childView.getSettings().setSupportZoom(true);
	        childView.getSettings().setBuiltInZoomControls(true);
	        childView.setWebViewClient(new FaceBookClient());
	        childView.setWebChromeClient(this);
	        childView.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT));


	        parentLayout.addView(childView);


	        childView.requestFocus();
	        webView.setVisibility(View.GONE);

	          /*I think this is the main part which handles all the log in session*/
	        WebView.WebViewTransport transport =(WebView.WebViewTransport)resultMsg.obj;
	        transport.setWebView(childView);
	        resultMsg.sendToTarget();
	        return true;
	    }


	    @Override
	    public void onProgressChanged(WebView view, int newProgress) {
	        MyActivity.setProgress(newProgress*100);
	    }

	    @Override
	    public void onCloseWindow(WebView window) {
		        parentLayout.removeViewAt(parentLayout.getChildCount()-1);
		        childView =null;
		        webView.setVisibility(View.VISIBLE);
		        webView.requestFocus();
		    }
	}

	private class FaceBookClient extends WebViewClient{
		
		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url) {
		        Log.i("REQUEST URL",url);
		        return false;
		    }   
	}
	
	//boolean loadingFinished = true;
	//boolean redirect = false;
//	private class WebClient extends WebViewClient {	
//		@Override
//	   public boolean shouldOverrideUrlLoading(WebView view, String urlNewString) {
//	       /*if (!loadingFinished) {
//	          redirect = true;
//	       }
//	
//		   loadingFinished = false;
//		   webView.loadUrl(urlNewString);*/
//		   view.loadUrl(urlNewString);
//		   return true;
//	   }
//	
//		/*
//	   @Override
//	   public void onPageStarted(WebView view, String url, Bitmap favicon) {
//		   super.onPageStarted(view, url, favicon);
//	        loadingFinished = false;
//	        //SHOW LOADING IF IT ISNT ALREADY VISIBLE  
//	    }
//		*/
//	   @Override
//	   public void onPageFinished(WebView view, String url) {
//			   /*
//		       if(!redirect){
//		          loadingFinished = true;
//		       }
//		
//		       if(loadingFinished && !redirect){
//		         
//				   Log.d("WebClient","page getContentHeight: " + Comentarios.this.webView.getWidth());
//				   Log.d("WebClient","page finished");
//				            
//				   view.loadUrl("javascript:onload=function(){if (document.getElementsByClassName == undefined) {document.getElementsByClassName = function(className){var hasClassName = new RegExp('(?:^|\\s)' + className + '(?:$|\\s)');var allElements = document.getElementsByTagName('*');var results = [];var element;for (var i = 0; (element = allElements[i]) != null; i++) {var elementClass = element.className;if (elementClass && elementClass.indexOf(className) != -1 && hasClassName.test(elementClass))results.push(element);};return results;};};};document.getElementsByClassName('fb_ltr')[0].style.width='900px';");
//		    	  
//		   } else{
//		      redirect = false; 
//		   }
//		   */
//			   //Log.d("WebClient","page getContentHeight: " + Comentarios.this.webView.getWidth());
//			   Log.d("WebClient","page finished");
//			            
//			   //view.loadUrl("javascript:onload=function(){if (document.getElementsByClassName == undefined) {document.getElementsByClassName = function(className){var hasClassName = new RegExp('(?:^|\\s)' + className + '(?:$|\\s)');var allElements = document.getElementsByTagName('*');var results = [];var element;for (var i = 0; (element = allElements[i]) != null; i++) {var elementClass = element.className;if (elementClass && elementClass.indexOf(className) != -1 && hasClassName.test(elementClass))results.push(element);};return results;};};};document.getElementsByClassName('fb_ltr')[0].style.width='900px';");
//		
//		}
//
//	}
	
//	private class MyPictureListener implements PictureListener {
//
//	    @Override
//	    public void onNewPicture(WebView view, Picture arg1) {
//	      // put code here that needs to run when the page has finished loading and
//	      // a new "picture" is on the webview.
//	    	
//	    				
//			DisplayMetrics displaymetrics = new DisplayMetrics();
//			getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
//			//int height = displaymetrics.heightPixels;
//			//int width = displaymetrics.widthPixels;
//			int width = (int) Math.ceil(displaymetrics.widthPixels * (displaymetrics.densityDpi / 160.0));
//			
//			//float widthInch = (displaymetrics.widthPixels / displaymetrics.ydpi);// * 25.4f;
//			
//			//pixel = (mm*dpi)/25.4
//			//1 mm =  	 3.779528 pixel			|| 		1 pixel =  	 0.264583 mm
//			
//			//int width = (int)(widthInch*96);///0.264583f);
//			//int width = webView.getWidth();
//			
//			//Resources r = getResources();
//			//float px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, displaymetrics.ydpi, r.getDisplayMetrics());
//			
//			Log.d("WebClientPicture","page getWidth: " + width + " - " + webView.getWidth() + " - " +displaymetrics.widthPixels);
//			//width = (int)(displaymetrics.widthPixels*displaymetrics.ydpi);
//			
//			
//			//if (Utiles.isTablet(MyActivity))
//			//width *= 0.72;
//				
//						
//			if (!ejecutoJs){
//				//view.loadUrl("javascript:onload=function(){if (document.getElementsByClassName == undefined) {document.getElementsByClassName = function(className){var hasClassName = new RegExp('(?:^|\\s)' + className + '(?:$|\\s)');var allElements = document.getElementsByTagName('*');var results = [];var element;for (var i = 0; (element = allElements[i]) != null; i++) {var elementClass = element.className;if (elementClass && elementClass.indexOf(className) != -1 && hasClassName.test(elementClass))results.push(element);};return results;};};}; document.getElementsByClassName('fb_ltr')[0].style.width=(window.devicePixelRatio>=1 ? "+displaymetrics.widthPixels+"/window.devicePixelRatio : "+displaymetrics.widthPixels+"*window.devicePixelRatio);");
//				ejecutoJs = true;
//				
//				//view.loadUrl("javascript:alert('R: '+window.devicePixelRatio+'W: '+document.getElementsByClassName('fb_ltr')[0].style.width);");//+'W: '+document.getElementsByClassName('fb_ltr')[0].style.width);");
//								
//				//view.loadUrl("javascript:alert((typeof window.innerWidth != 'undefined') ? window.innerWidth : (typeof document.documentElement != 'undefined' && typeof document.documentElement.clientWidth != 'undefined' && document.documentElement.clientWidth != 0) ? document.documentElement.clientWidth : document.getElementsByTagName('body')[0].clientWidth );");
//				
//				//view.loadUrl("javascript:document.getElementsByClassName('fb_ltr')[0].style.width=w;");
//				
//				//view.loadUrl("javascript:alert('W js:'+w);");
//				
//				Log.d("WebClientPicture","page width: " + width);				
//			}
//	    }    
//	} 

	
	@Override
    public void onBackPressed() {
	    if(childView != null && parentLayout.getChildCount()==2){
	        childView.stopLoading();
	        parentLayout.removeViewAt(parentLayout.getChildCount()-1);
	        if(webView.getVisibility() == View.GONE)
	            webView.setVisibility(View.VISIBLE);
	    }else{          
	        super.onBackPressed();
	    }
	}
	
	

	
}
